package org.minuframework.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Maps;

/**
 * 跨域过滤器
 * @author 米mi
 */
public class HttpCORSFilter implements Filter {
    
    public static final String ACCESS_CONTROL_ALLOW_ORIGIN         = "Access-Control-Allow-Origin";
    public static final String ACCESS_CONTROL_ALLOW_ORIGIN_RESULT  = "*";
    public static final String ACCESS_CONTROL_ALLOW_METHODS        = "Access-Control-Allow-Methods";
    public static final String ACCESS_CONTROL_ALLOW_METHODS_RESULT = "POST, GET, OPTIONS, DELETE, PUT";
    public static final String ACCESS_CONTROL_ALLOW_HEADERS        = "Access-Control-Allow-Headers";
    public static final String ACCESS_CONTROL_ALLOW_HEADERS_RESULT = "x-requested-with,content-type";
    
    private Map<String, Object> params;
    
    public Map<String, Object> getRepository() {
        if (params == null) {
            params = Maps.newHashMap();
        }
        return params;
    }
    
    @Override
    public void init(FilterConfig config) throws ServletException {
        Enumeration<String> initParas = config.getInitParameterNames();
        while (initParas.hasMoreElements()) {
            String key = initParas.nextElement();
            String value = config.getInitParameter(key);
            getRepository().put(key, value);
        }
        if (getRepository().isEmpty()) {
            getRepository().put(ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_ALLOW_ORIGIN_RESULT);
            getRepository().put(ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_METHODS_RESULT);
            getRepository().put(ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_HEADERS_RESULT);
        }
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        for (Entry<String, Object> entry : getRepository().entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().toString();
            httpResponse.setHeader(key, value);
        }
        chain.doFilter(httpRequest, httpResponse);
    }
    
    @Override
    public void destroy() {}
    
}
